import React from 'react'
import { DownOutlined } from '@ant-design/icons'
import { Button, Space, Dropdown, Select ,message} from 'antd'
import { useState, useEffect } from 'react'
import { useSearchParams, useNavigate } from 'react-router-dom'
import '../assets/css/my.css'
import { getOperator } from '../assets/js/phone'
import axios from 'axios'


export default function Login() {

  const phoneChoose = [
    { label: '移动', value: '移动' },
    { label: '联通', value: '联通' },
    { label: '电信', value: '电信' }
  ]
  let [selectValue, setSelectValue] = useState()  //选择的运营商
  const [phoneNumber, setPhoneNumber] = useState('');  //输入的手机号
  const [operator, setOperator] = useState('');  //输入的手机号对应的运营商
  const [tipText, setTipText] = useState(''); // 提示信息的状态
  let [isLogin, setIslogin] = useState(true)
  let [isrejest, setRejest] = useState(false)
  let yan = React.createRef()

  let [pwd,setPwd] = useState('') //密码框
  let [yanma,setYanma] = useState('') //输入的验证码
  let [yanzhengma, setYanzhengma] = useState('获取验证码')
  let [checkedTips, setCheckedTips] = useState('')
  let [newPsd, setNewPsd] = useState('')  //忘记密码时新密码
  let [newquePsd, setNewQuePsd] = useState('')  //忘记密码时确认新密码

  let [obj, setObj] = useSearchParams()
  let nav = useNavigate()
  let path = obj.get('path') || '/'

  let phonetips = React.createRef()
  const [isChecked, setIsChecked] = useState(false); //是否同意协议
  const [twopwdTips, setTwopwdTips] = useState(''); //两次输入密码不一致提示
  //验证码按钮文字状态
  const getCodeState = () => {
    setYanzhengma('60S');
    let s = 60;
    let clear = setInterval(() => {
      s--;
      setYanzhengma(s + 'S');
      if (s <= 0) {
        clearInterval(clear);
        setYanzhengma('获取验证码');

      }
    }, 1000);
  }

  // 判断选择的运营商和输入的手机号是否一致
  const checkPhone = () => {
    const newOperator = getOperator(phoneNumber);
    setOperator(newOperator);
  }
  const handleCheckboxChange = (event) => {
    setIsChecked(event.target.checked);
};



  useEffect(() => {
    if (operator) {
      console.log(selectValue, operator);
      if (selectValue === operator) {
        setTipText('');
      } else {
        setTipText('手机号格式错误');
      }
    }
  }, [operator, selectValue]);

  useEffect(() => {
    if (!isLogin) {
      console.log(111);
      setPhoneNumber('');
      setSelectValue('');
      setTipText('')
    }
  }, [isLogin, isrejest])

  const getImg = (url) => {
    return new URL(url, import.meta.url).href
  }

  // 登录判断
  const login = (phone)=>{
    axios.get('http://172.16.17.115:8080/loginPhone',{
      params:{
        phone:phone
      }
    }).then(res=>{
      console.log(res.data);
      if(res.data.length == 0){
        message.open({
          type:'error',
          content:'该账号不存在，请先注册',
          duration:1
        })
      }else{
        let item = res.data[0];
        if(item.password ==pwd && !isChecked){
          setCheckedTips('请勾选同意用户协议')
        }else if(item.password ==pwd && isChecked){
          localStorage.setItem('user',JSON.stringify(item))
          nav('/home/zichan/lou')
        }else{
          message.open({
            type:'error',
            content:'密码错误',
            duration:1
          })
        }
      }
    })
  }

  // 点击忘记密码，修改密码
  const changePwd = (phoneNumber,yanma,newPsd,newquePsd)=>{

    if(phoneNumber&&yanma&&newPsd&&newquePsd&&isChecked ){
      if(newPsd==newquePsd){
        axios.post('http://172.16.17.115:8080/updateuserPwd',{
            phone:phoneNumber,
            newPassword:newPsd
        }).then(res=>{
          console.log(res.data);
          
          message.open({
            type:'success',
            content:'修改密码成功',
            duration:1
          })
          setPhoneNumber('')
          setYanma('')
          setNewPsd('')
          setNewQuePsd('')
          setIsChecked(false)
          setTwopwdTips('')
          setTipText('')
        })
      }else{
        setTwopwdTips('两次密码不一致')
      }
    }else{
      setTwopwdTips('请输入完整信息')
    }
    
  }


  // 注册
  const rigest = ()=>{
    if(phoneNumber&&yanma&&newPsd&&newquePsd&&isChecked){
      if(newPsd==newquePsd){
        axios.post('http://172.16.17.115:8080/adduser',{
          telphone:phoneNumber,
          password:newPsd
        }).then(res=>{
          message.open({
            type:'success',
            content:'注册成功',
            duration:1
          })
          setPhoneNumber('')
          setYanma('')
          setNewPsd('')
          setNewQuePsd('')
          setIsChecked(false)
          setTwopwdTips('')
          setTipText('')
        })
      }else{
        setTwopwdTips('两次密码不一致')
      }
    }else{
      setTwopwdTips('请输入完整信息')
    }
  }



  return (
    <div className='container login'>
      <div className="top">
        <img className='logo' src={getImg('https://s21.ax1x.com/2024/11/29/pA5G78K.png')} alt="" />
        <span>资产管理</span>
      </div>
      <div className="content">
        <div className="login">
          <div className="login-name">{isrejest ? '注册' : isLogin ? '登录' : '忘记密码'}</div>
          <form action="">
            <div className="phone">
              <Select
                style={{
                  width: 120,
                  height: 36
                }}
                allowClear
                options={phoneChoose}
                placeholder="中国+86"
                onChange={(selectValue) => {
                  setSelectValue(selectValue)
                }}
              />

              <input type="text" placeholder='请输入手机号'
                value={phoneNumber}
                onBlur={checkPhone}
                onChange={(e) => {
                  setPhoneNumber(e.target.value)

                }} />
            </div>

            <span ref={phonetips} className='phone-tips'>{tipText}</span>

            {!isLogin && (<label htmlFor="" className='getyan phone' >
              <input type="text" value={yanma} onChange={(e)=>{setYanma(e.target.value)}} placeholder='请输入验证码' />
              <span ref={yan} onClick={() => {
                yan.current.style.background = '#f4f6fa';
                yan.current.style.fontSize = '14px';
                yan.current.style.color = '#707481';; getCodeState()
              }}>{yanzhengma}</span>
            </label>)}

            {!isLogin && <span className='phone-tips'></span>}


            {!isLogin && (<label htmlFor="" className='pwd' >
              <input type="text" value={newPsd} onChange={(e)=>{setNewPsd(e.target.value)}} placeholder='请输入密码，包含数字和字母的8-20位密码' />
            </label>)}

            {!isLogin && <span className='phone-tips'></span>}

            {!isLogin && (<label htmlFor="" className='pwd' >
              <input type="text" value={newquePsd} onChange={(e)=>{setNewQuePsd(e.target.value)}} placeholder='确认密码' />
            </label>)}

            {isLogin && (<label htmlFor="" className='pwd' >
              <input type="text" placeholder='请输入密码' value={pwd} onChange={(e) => {setPwd(e.target.value)}}/>
            </label>)}

            <span className='phone-tips'>{twopwdTips}</span>

            <div className="tips">
              <input type="checkbox" onChange={handleCheckboxChange}/><span>已阅读并同意<a href="">《用户使用协议》</a></span>
            </div>

            <span className='phone-tips'>{checkedTips}</span>


            <div className='btn' onClick={() => {
              // localStorage.setItem('token', 'CVBNKFVCDTYKCJ')
              // nav('/home/zichan/lou')
              if(isLogin){
                login(phoneNumber)
              }
              if(!isLogin&&isrejest){
                rigest()
              }
              if(!isLogin &&!isrejest){
                changePwd(phoneNumber,yanma,newPsd,newquePsd)
              }
            }}>
              {isrejest ? '注册' : isLogin ? '登录' : '确认修改'}
            </div>
            {isLogin && (<div className="small">
              <span onClick={() => { setIslogin(false); setPhoneNumber(''); setSelectValue(''); setTipText('') }}>忘记密码</span>
              <span onClick={() => { setRejest(true); setIslogin(false) }}>免费注册</span>
            </div>)}
            {!isLogin && (<div className="havesmall">
              已有账号，立即<span onClick={() => setIslogin(true)}>登录</span>
            </div>)}
          </form>




        </div>
        <div className="fangzi">
          <img src={getImg('https://s21.ax1x.com/2024/11/29/pA5GHgO.png')} alt="" />
        </div>
      </div>
      <div className="bottom">
        2018-2019 北京乐闻诺科技有限公司 京ICP备19041303号
      </div>
    </div>
  )
}
